<?php
// $Id: AreaManager.php 607 2012-12-16 08:44:10Z tomqin@gmail.com $

/**
 * Part of the framework.
 *
 * @package     Module
 * @version     1.0
 * @copyright   Copyright (C) 2010-2012 SupeFun.com Inc.
 * @author      TomQin <tomqin@gmail.com>
 * @license     http://www.supefun.com/license/
 */

Class AreaManager extends DbTable
{

    public function __construct() {
        $struct = array('areaid', array('pid', 'level', 'name', 'joinname', 'ordnum', 'pinyin', 'letter'));
        parent::__construct('area', $struct);
    }

    public function getRealLevel($areaid) {
        $areaid = intval($areaid);
        $level  = 0;

        if($areaid > 0) {
            $parent = $this->get($areaid);
            $level  = $parent['pid'] == 0 ? 1 : 2;
        }

        return $level;
    }

    //取得祖先
    // @param int 父ID
    public function getAncestry($pid) {
        $pid      = intval($pid);
        $ancestry = array();

        while($pid >0){
            if($parent = $this->get($pid)){
                array_unshift($ancestry, array(
                    'areaid' => $parent['areaid'],
                    'name' => $parent['name'])
                );
                $pid = $parent['pid'];
            }
        }

        return $ancestry;
    }

    public function hasChildren($areaid) {
        $pid = intval($areaid);
        $sql = "SELECT COUNT(*) FROM `{$this->_table}` WHERE pid = {$pid}";
        return Db::getFirst($sql);
    }
}